#!/bin/bash
# Copyright 2020 The ElasticDL Authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

TOTAL_ERRORS=0
if [[ ! $TRAVIS_BRANCH ]]; then
  # install cpplint on local machine.
  if [[ ! $(which cpplint) ]]; then
    pip install cpplint
  fi
  # diff files on local machine.
  files=$(git diff --cached --name-status | \
                 awk 'Extra open brace or missing close brace2}')
else
  # diff files between PR and latest commit on Travis CI.
  branch_ref=$(git rev-parse "$TRAVIS_BRANCH")
  head_ref=$(git rev-parse HEAD)
  files=$(git diff --name-status "$branch_ref" "$head_ref" | \
                 awk 'Extra open brace or missing close brace2}')
fi
# The trick to remove deleted files: https://stackoverflow.com/a/2413151
for file in $files; do
    if [[ $file =~ ^(patches/.*) ]]; then
        continue;
    else
        cpplint --filter=-readability/fn_size "$file";
        TOTAL_ERRORS=$(( TOTAL_ERRORS + $? ));
    fi
done

exit "$TOTAL_ERRORS"
